package com.idbk.chargestation.activity.charge;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivityHelp;
import com.idbk.chargestation.adapter.GunGridViewAdapter;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonGunInfor;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.EToolbar2;

import java.util.ArrayList;
import java.util.List;

/**
 * 多枪界面
 * Created by wuz on 2019/1/12.
 */

public class ActivityMultiGun extends BaseActivity implements View.OnClickListener {

    /**
     * 数据刷新时间
     */
    public final static int DOUBLE_GUN_REFRESH = 5000;

    private Context mContext;
    private TextView mPoint, mSn, mStyle, mCost, mPerformance;
    private TextView mGunInfor;
    private TextView mTip, mConnect, mNext;
    private JsonQrScan mQrScanData;
    private GridView mGridView;
    private GunGridViewAdapter mAdapter;
    private int gunNum = 0; //枪的数量
    private LinearLayout mLinearTip;
    private SpannableString spanATip;
    private String mPileSn, mTextTip;
    private int gunChoose = 0;
    private int positionChoose = -1;
    private List<JsonGunInfor> mInforList;
    private String speed;

    private Handler handler;

    /**
     * 默认选择的枪号
     */
    private int mGunNum = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_multi_gun);
        mContext = this;
        setupView();

        setupData();
    }

    private void setupView(){
        mToolbar2 = (EToolbar2) findViewById(R.id.tj_toolbar2);
        mToolbar2.setTitle(getToolBarTitle());
        mToolbar2.getBackView().setOnClickListener(this);

        mPoint = (TextView) findViewById(R.id.point);
        mSn = (TextView) findViewById(R.id.sn);
        mStyle = (TextView) findViewById(R.id.style);
        mCost = (TextView) findViewById(R.id.cost);
        mPerformance = (TextView) findViewById(R.id.performance);

        mGunInfor = (TextView) findViewById(R.id.gun_inf);
        mConnect = (TextView) findViewById(R.id.activity_connect);
        mNext = (TextView) findViewById(R.id.textview_next);
        mTip = (TextView) findViewById(R.id.activity_tip);
        mLinearTip = (LinearLayout) findViewById(R.id.layout_double);

        if (mConnect != null && mNext != null) {
            mConnect.setOnClickListener(this);
            mNext.setOnClickListener(this);
            // 初始化不给点击，获取枪的实时状态后再运行点击
            mNext.setClickable(false);
        }
    }

    private void setupData(){
        mQrScanData = getIntent().getParcelableExtra(JsonQrScan.KEY);
        gunChoose = 0; //已连接枪数

        mInforList = new ArrayList<JsonGunInfor>();
        mInforList.addAll(mQrScanData.gunInfos);
        speed = mQrScanData.chargeSpeed;
        setGunSort(mInforList);

        setGridView();
        mPoint.setText(mQrScanData.pointName);
        mSn.setText(mQrScanData.pileSn);
        mStyle.setText(mQrScanData.performance);
        mCost.setText(mQrScanData.getPriceTypeString());
        mPerformance.setText(mQrScanData.chargeSpeed);

        mPileSn = mQrScanData.pileSn;
        mTextTip = "请将充电枪与车辆充电口正确连接";

        gunNum = mInforList.size();
        SpannableString spanTip = new SpannableString("该类型电桩自带 "+gunNum+" 把充电枪可供使用:");
        spanTip.setSpan(new AbsoluteSizeSpan(12, true), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)),
                0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanTip.setSpan(new AbsoluteSizeSpan(14, true), 8, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_theme)),
                8, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanTip.setSpan(new AbsoluteSizeSpan(12, true), 9, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)),
                9, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mGunInfor.setText(spanTip);


        for (int i = 0; i < gunNum; i++){
            if (mInforList.get(i).gunStatus ==  JsonPointPile.STATUS_WAIT){
                gunChoose++;
            }
        }
        if (gunChoose == 1){
            for (int i = 0; i < gunNum; i++){
                if (mInforList.get(i).gunStatus ==  JsonPointPile.STATUS_WAIT){
                    mGunNum = mInforList.get(i).gunNum;
                    spanATip = spanGun("车辆与 枪"+mGunNum+" 连接成功，请点击下一步");
                }
            }
            mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
            mNext.setClickable(true);
            mConnect.setVisibility(View.GONE);
            mLinearTip.setVisibility(View.GONE);
            mTip.setVisibility(View.VISIBLE);
            mTip.setText(spanATip);
        }else if (gunChoose >= 2 && positionChoose == -1){
            mTip.setVisibility(View.GONE);
            mConnect.setVisibility(View.GONE);
            mLinearTip.setVisibility(View.VISIBLE);
        }

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (gunChoose >= 2 && mInforList.get(position).gunStatus ==  JsonPointPile.STATUS_WAIT){
                    mGunNum = mInforList.get(position).gunNum;
                    spanATip = spanGun("车辆与 枪"+mGunNum+" 连接成功，请点击下一步");
                    positionChoose = position;
                    mAdapter.setSeclection(position);
                    mAdapter.notifyDataSetChanged();
                    mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
                    mNext.setClickable(true);
                    mConnect.setVisibility(View.GONE);
                    mLinearTip.setVisibility(View.GONE);
                    mTip.setVisibility(View.VISIBLE);
                    mTip.setText(spanATip);

                }
            }
        });

        handler = new Handler();
    }

    private void setGridView(){
        mGridView = (GridView)findViewById(R.id.gridView);
        mAdapter = new GunGridViewAdapter(mContext, mInforList, speed);
        mGridView.setAdapter(mAdapter);
    }

    private void setGunSort(List<JsonGunInfor> list){
        int num1, num2;
        JsonGunInfor sign;
        for(int i = 0; i < list.size()-1; i++){
            for (int j = i+1; j < list.size(); j++){
                num1 = list.get(i).gunNum;
                num2 = list.get(j).gunNum;
                if (num2 < num1){
                    sign = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, sign);
                }
            }
        }
    }

    private void setRefreshData(){
        gunChoose = 0;

        for (int i = 0; i < gunNum; i++){
            if (mInforList.get(i).gunStatus ==  JsonPointPile.STATUS_WAIT){
                gunChoose++;
            }
        }
        if (gunChoose == 1){
            for (int i = 0; i < gunNum; i++){
                if (mInforList.get(i).gunStatus ==  JsonPointPile.STATUS_WAIT){
                    mGunNum = mInforList.get(i).gunNum;
                }
            }
            mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
            mNext.setClickable(true);
            mConnect.setVisibility(View.GONE);
            mLinearTip.setVisibility(View.GONE);
            mTip.setVisibility(View.VISIBLE);
            mTip.setText(spanATip);
        }else if (gunChoose >= 2 && positionChoose == -1){
            mTip.setVisibility(View.GONE);
            mConnect.setVisibility(View.GONE);
            mLinearTip.setVisibility(View.VISIBLE);
        }

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (gunChoose >= 2 && mInforList.get(position).gunStatus ==  JsonPointPile.STATUS_WAIT){
                    mGunNum = mInforList.get(position).gunNum;
                    spanATip = spanGun("车辆与 枪"+mGunNum+" 连接成功，请点击下一步");
                    positionChoose = position;
                    mAdapter.setSeclection(position);
                    mAdapter.notifyDataSetChanged();
                    mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
                    mNext.setClickable(true);
                    mConnect.setVisibility(View.GONE);
                    mLinearTip.setVisibility(View.GONE);
                    mTip.setVisibility(View.VISIBLE);
                    mTip.setText(spanATip);
                }
            }
        });
    }

    @Override
    protected void onStart() {
        if(AppContext.getInstance().isLogin()) {
            handler.post(runnable);
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        handler.removeCallbacks(runnable);
        super.onStop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                dialogTip();
                break;
            case R.id.activity_connect:
                Intent intent = new Intent(ActivityMultiGun.this, ActivityHelp.class);
                startActivity(intent);
                break;
            case R.id.textview_next:
                goToCharging();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        dialogTip();
        return super.onKeyDown(keyCode, event);
    }

    public SpannableString spanGun(String str) {
        SpannableString span = new SpannableString(str);
        span.setSpan(new AbsoluteSizeSpan(12, true), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(14, true), 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_theme)), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(12, true), 6, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)), 6, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    }

    private void dialogTip() {
        new AlertDialog.Builder(ActivityMultiGun.this)
                .setTitle(R.string.common_dialog_tip)
                .setMessage("是否确定退出当前的操作？")
                .setCancelable(false)
                .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        finish();
                    }
                })
                .setNegativeButton(R.string.common_cancel, null)
                .create().show();
    }

    private void goToCharging() {
        handler.removeCallbacks(runnable);

        //判断交直流
        if (mQrScanData == null) {
            Toast.makeText(this, "参数错误，请返回重新连接！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mQrScanData.isDcCharging()) {
            //直流
            Intent intent = new Intent(this, ActivityChargingDc.class);
            intent.putExtra("gunNum", mGunNum);
            intent.putExtra(JsonQrScan.KEY, mQrScanData);
            intent.putExtra(ActivityChargingDc.KEY_CHARGE_ACTION, ActivityChargingDc.CHARGE_ACTION_WAIT);
            startActivity(intent);
            finish();
        } else if (mQrScanData.isAcCharging()) {
            //交流
            Intent intent = new Intent(this, ActivityChargingAc.class);
            intent.putExtra("gunNum", mGunNum);
            intent.putExtra(JsonQrScan.KEY, mQrScanData);
            intent.putExtra(ActivityChargingAc.KEY_CHARGE_ACTION, ActivityChargingAc.CHARGE_ACTION_WAIT);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "无法判断充电桩类型！", Toast.LENGTH_SHORT).show();
        }
    }

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            APIForCharge.qrScan(mPileSn, new EHttpResponse() {

                @Override
                public void onEResponse(String response) {
                    JsonQrScan result = GsonUtils.toBean(JsonQrScan.class, response);
                    if (result == null) {
                        Toast.makeText(ActivityMultiGun.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();

                    } else if (result.status == GlobalResult.OK.getStatus()) {
                        Log.d("dededede=====", 1212121+"");
                        mInforList.clear();
                        mInforList.addAll(result.gunInfos);
                        setGunSort(mInforList);
                        setRefreshData();
                        mAdapter.notifyDataSetChanged();
                        handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);

                    } else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()) {
                        handler.removeCallbacks(runnable);//停止请求枪刷新
                        AppContext.getInstance().clearLoginState();
                        jumpToLogin(ActivityMultiGun.this, true);

                    } else {
                        Toast.makeText(ActivityMultiGun.this, result.message, Toast.LENGTH_SHORT).show();
                        handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);
                    }
                }

                @Override
                public void onEErrorResponse(VolleyError error) {
                    handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);
                    Toast.makeText(ActivityMultiGun.this, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onEFinish() {
                    super.onEFinish();
                }
            });

        }
    };

}
